package paper.dao.impl;

import java.util.List;

import keter.dao.base.KeterAbstractDao;
import keter.dao.org.AccountDao;
import keter.domain.Account;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import paper.dao.UserDao;
import paper.domain.User;

@Repository
public class UserDaoImpl extends KeterAbstractDao<User> implements UserDao {

	@Autowired
	private AccountDao accountDao;

	@Override
	public User findByLogin(String login) {
		Account account = accountDao.findByName(login);
		return account != null ? findByAccount(account) : null;
	}

	/**
	 * <p>
	 * Method ：UserWithAccount
	 * <p>
	 * Description :
	 * 
	 * @param 返回一个包含当前账户且ID为空的用户对象
	 * @return
	 * @author gulixing@msn.com
	 * @version 1.0.0
	 */
	private User IdEmptyUserWithCurrentAccount(Account a) {
		User user = new User();
		user.setAccount(a);
		return user;
	}

	@Override
	public User findByAccount(Account account) {
		User u = getSingleResult("from User u where u.account.id = :accountId",
				wrap("accountId"), wrap(account.getId()));
		return u == null ? IdEmptyUserWithCurrentAccount(account) : u;
	}

	@Override
	public List<User> findByTeacher(Long id) {
		return getResultList(
				"from User s where s.teacher.id = :id order by s.graduate",
				wrap("id"), wrap(id));
	}

	@Override
	public List<User> findUserByUnitId(Long id) {
		return getResultList("from User s where s.account.unit.id = :id",
				wrap("id"), wrap(id));
	}
}